잠시만 기다려 주세요

     '대한민국이 더이상 발전하지 못하는 것은 부패한 언론들의 쓰레기짓 때문이다.'
전체검색 :  
이번주 로또 및 연금번호 발생!!   |  HOME   |  여기는?   |  바다물때표   |  알림 (16)  |  여러가지 팁 (1054)  |  추천 및 재미 (150)  |  자료실 (22)  |  
시사, 이슈, 칼럼, 평론, 비평 (582)  |  끄적거림 (127)  |  문예 창작 (702)  |  바람 따라 (69)  |  시나리오 (760)  |  드라마 대본 (248)  |  
살인!


    postgresql

postgresql - Using PostgreSQL Arrays, 배열 필드 사용하기... 배열형 컬럼 사용하기...
이 름 : 바다아이   |   조회수 : 9220         짧은 주소 : https://www.bada-ie.com/su/?551591780218
일단 테이블 하나 만들어 보겠습니다. 배열 필드를 만들었습니다.

CREATE TABLE aaa (
     title text NOT NULL PRIMARY KEY,
     tags  text[] NOT NULL DEFAULT '{}'::text[]
 );


데이터를 하나 넣어보죠..

INSERT INTO aaa (title, tags) VALUES ('Using PostgreSQL Arrays with Golang', '{"postgres","golang"}');


데이터를 가져와 보면 잘 들어가 있군요.. {} 괄호 안에 배열이 잘 보입니다.

select * from aaa;

                title                |       tags        
-------------------------------------+-------------------
 Using PostgreSQL Arrays with Golang | {postgres,golang}
(1개 행)


데이터를 몇개 더 넣어볼까요...

INSERT INTO aaa (title, tags) VALUES ('Using PostgreSQL Arrays with Golang2', '{"postgres2","golang2"}');
INSERT INTO aaa (title, tags) VALUES ('Using PostgreSQL Arrays with Golang3', '{"postgres3","golang3"}');
INSERT INTO aaa (title, tags) VALUES ('Using PostgreSQL Arrays with Golang4', '{"postgres","golang", "what"}');
INSERT INTO aaa (title, tags) VALUES ('Using PostgreSQL Arrays with Golang5', '{"postgres7","golang7", "what"}');


결과를 보면 잘 들어가 있네요....

select * from aaa;

                title                 |           tags           
--------------------------------------+--------------------------
 Using PostgreSQL Arrays with Golang  | {postgres,golang}
 Using PostgreSQL Arrays with Golang2 | {postgres2,golang2}
 Using PostgreSQL Arrays with Golang3 | {postgres3,golang3}
 Using PostgreSQL Arrays with Golang4 | {postgres,golang,what}
 Using PostgreSQL Arrays with Golang5 | {postgres7,golang7,what}
(5개 행)


배열의 개수를 한번 세어볼까요? 1차원 배열이니까... 숫자 1을 넣었습니다. array_length 함수는 다차원에서도 사용 가능합니다.

SELECT title, array_length(tags, 1) FROM aaa;
                title                 | array_length 
--------------------------------------+--------------
 Using PostgreSQL Arrays with Golang  |            2
 Using PostgreSQL Arrays with Golang2 |            2
 Using PostgreSQL Arrays with Golang3 |            2
 Using PostgreSQL Arrays with Golang4 |            3
 Using PostgreSQL Arrays with Golang5 |            3
(5개 행)


cardinality 함수로도 개수 파악이 가능합니다.

SELECT title, cardinality(tags) FROM aaa;
                title                 | cardinality 
--------------------------------------+-------------
 Using PostgreSQL Arrays with Golang  |           2
 Using PostgreSQL Arrays with Golang2 |           2
 Using PostgreSQL Arrays with Golang3 |           2
 Using PostgreSQL Arrays with Golang4 |           3
 Using PostgreSQL Arrays with Golang5 |           3
(5개 행)


what 이라는 특정 배열 요소가 존재하면 출력해 주는 예제입니다. 문자열 검색으로 생각하면 안됩니다.
연산자 <@ 는 크다 작다가 아니라 방향입니다. tags @> '{"what"}' 이렇게 해도 같은 결과가 나옵니다.

SELECT title, tags FROM aaa WHERE '{"what"}' <@ tags;
                title                 |           tags           
--------------------------------------+--------------------------
 Using PostgreSQL Arrays with Golang4 | {postgres,golang,what}
 Using PostgreSQL Arrays with Golang5 | {postgres7,golang7,what}
(2개 행)


만약 배열 요소 두개를 적어주면 두개다 존재해야 출력됩니다. and 개념이죠...

SELECT title, tags FROM aaa WHERE '{"postgres", "golang"}' <@ tags;
                title                 |          tags          
--------------------------------------+------------------------
 Using PostgreSQL Arrays with Golang  | {postgres,golang}
 Using PostgreSQL Arrays with Golang4 | {postgres,golang,what}
(2개 행)


만약 or 개념으로 검색하려면.... 연산자를 && 를 사용합니다.

SELECT title, tags FROM aaa WHERE '{"what", "golang"}' && tags;
                title                 |           tags           
--------------------------------------+--------------------------
 Using PostgreSQL Arrays with Golang  | {postgres,golang}
 Using PostgreSQL Arrays with Golang4 | {postgres,golang,what}
 Using PostgreSQL Arrays with Golang5 | {postgres7,golang7,what}
(3개 행)


그렇다면 배열을 풀어서 레코드로 가져오려면..... unnest 를 사용하면 풀어서 하나씩 다 보여줍니다.

SELECT title, unnest(tags) FROM aaa;
                title                 |  unnest   
--------------------------------------+-----------
 Using PostgreSQL Arrays with Golang  | postgres
 Using PostgreSQL Arrays with Golang  | golang
 Using PostgreSQL Arrays with Golang2 | postgres2
 Using PostgreSQL Arrays with Golang2 | golang2
 Using PostgreSQL Arrays with Golang3 | postgres3
 Using PostgreSQL Arrays with Golang3 | golang3
 Using PostgreSQL Arrays with Golang4 | postgres
 Using PostgreSQL Arrays with Golang4 | golang
 Using PostgreSQL Arrays with Golang4 | what
 Using PostgreSQL Arrays with Golang5 | postgres7
 Using PostgreSQL Arrays with Golang5 | golang7
 Using PostgreSQL Arrays with Golang5 | what
(12개 행)


중복값을 제거하고 가져온다면..... 참고로 distinct 는 가져온 모든 필드에서 다 일치해야 중복을 제거합니다. 
그래서 distinct unnest(tags), title 이렇게 하면 두 필드다 중복되어야 한개만 출력합니다. 참고하세요...
아래는 tags 만 중복제거 합니다.

SELECT distinct unnest(tags) FROM aaa;
  unnest   
-----------
 postgres
 postgres3
 postgres7
 what
 golang7
 postgres2
 golang
 golang2
 golang3
(9개 행)


중복 제거 후 가져온 값을 배열로 만들 수도 있습니다.

select array(SELECT distinct unnest(tags) FROM aaa);
                                    array                                     
------------------------------------------------------------------------------
 {postgres,postgres3,postgres7,what,golang7,postgres2,golang,golang2,golang3}
(1개 행)


조금더 응용해 보면.... tag 를 중복제거 후 tag와 그 중복된 개수를 구합니다.

WITH p AS (SELECT title, unnest(tags) AS tag FROM aaa)
SELECT tag, count(tag) FROM p GROUP BY tag;
    tag    | count 
-----------+-------
 postgres  |     2
 postgres3 |     1
 postgres7 |     1
 what      |     2
 golang7   |     1
 postgres2 |     1
 golang    |     2
 golang2   |     1
 golang3   |     1
(9개 행)


배열을 추가 할 수도 있습니다.

UPDATE aaa SET tags = array_append(tags, 'legacy');

select * from aaa;
                title                 |              tags               
--------------------------------------+---------------------------------
 Using PostgreSQL Arrays with Golang  | {postgres,golang,legacy}
 Using PostgreSQL Arrays with Golang2 | {postgres2,golang2,legacy}
 Using PostgreSQL Arrays with Golang3 | {postgres3,golang3,legacy}
 Using PostgreSQL Arrays with Golang4 | {postgres,golang,what,legacy}
 Using PostgreSQL Arrays with Golang5 | {postgres7,golang7,what,legacy}
(5개 행)


수정도 가능합니다.

UPDATE aaa SET tags = array_replace(tags, 'golang', 'go');

select * from aaa;
                title                 |              tags               
--------------------------------------+---------------------------------
 Using PostgreSQL Arrays with Golang  | {postgres,go,legacy}
 Using PostgreSQL Arrays with Golang2 | {postgres2,golang2,legacy}
 Using PostgreSQL Arrays with Golang3 | {postgres3,golang3,legacy}
 Using PostgreSQL Arrays with Golang4 | {postgres,go,what,legacy}
 Using PostgreSQL Arrays with Golang5 | {postgres7,golang7,what,legacy}
(5개 행)


조건 걸어서 수정해 봅니다.

UPDATE aaa SET    tags = array_replace(tags, 'go', 'go2') WHERE  '{"go"}' <@ tags;

select * from aaa;
                title                 |              tags               
--------------------------------------+---------------------------------
 Using PostgreSQL Arrays with Golang2 | {postgres2,golang2,legacy}
 Using PostgreSQL Arrays with Golang3 | {postgres3,golang3,legacy}
 Using PostgreSQL Arrays with Golang5 | {postgres7,golang7,what,legacy}
 Using PostgreSQL Arrays with Golang  | {postgres,go2,legacy}
 Using PostgreSQL Arrays with Golang4 | {postgres,go2,what,legacy}
(5개 행)


일반 언어에서 선언한 배열을 넣으려면...
아래는 golang 에서 예를 들어 본 것입니다...

package main

import (
	"database/sql"
	"fmt"

	"github.com/lib/pq"
)

func main() {
	dbinfo := fmt.Sprintf("host=localhost user=유저 password=패스워드 dbname=디비명 sslmode=disable")
	db, err := sql.Open("postgres", dbinfo)
	err = db.Ping()

	// "ins" is the SQL insert statement
	ins := "INSERT INTO aaa (title, tags) VALUES ($1, $2)"

	// "tags" is the list of tags, as a string slice
	tags := []string{"go", "goroutines", "queues"}

	// the pq.Array function is the secret sauce
	_, err = db.Exec(ins, "Job Queues in Go3", pq.Array(tags))

	_ = err

	db.Close()
}

| |





      1 page / 2 page
번 호 카테고리 제 목 이름 조회수
45 postgresql postgresql ... postgresql 14 .. postgresql.conf port 5432 .. 바다아이 673
44 postgresql , count(*) .... 바다아이 6852
43 postgresql How to do an update + join in PostgreSQL?, 바다아이 6083
42 postgresql sequence(퀀) 바다아이 7716
41 postgresql , , , index create, , 바다아이 8098
40 postgresql postgresql log_timezone .... 바다아이 6500
39 postgresql postgresql SEQUENCE reset .... 바다아이 8337
38 postgresql [PostgreSql] WITH , , Operator 바다아이 7728
37 postgresql postgresql for, foreach , 바다아이 9284
36 postgresql postgresql , , into ... 바다아이 9282
35 postgresql postgresql PL/pgSQL - SQL Procedural Language, , 바다아이 10696
34 postgresql postgresql ... .. , , 바다아이 11711
33 postgresql postgresql CSV export/import 바다아이 8514
32 postgresql postgresql tablespace , .... 바다아이 12836
31 postgresql postgresql 10 partitioning, ... , ... 바다아이 9253
현재글 postgresql Using PostgreSQL Arrays, ... ... 바다아이 9221
29 postgresql PostgreSQL (TRIGGER) (function) 바다아이 8983
28 postgresql Optimize and Improve PostgreSQL Performance with VACUUM, ANALYZE, and REINDEX 바다아이 9632
27 postgresql postgresql tuple . vacuumdb .. , . 바다아이 9029
26 postgresql postgresql , .. 바다아이 9224
25 postgresql postgresql , size, 바다아이 11223
24 postgresql postgresql , , .... 바다아이 8270
23 postgresql PostgreSQL Replication, , , master, slave 바다아이 10770
22 postgresql postgresql case 바다아이 8138
21 postgresql postgresql with 바다아이 8575
20 postgresql postgresql , , string 바다아이 11480
19 postgresql Postgresql partitioning table , , , 바다아이 9072
18 postgresql PostgreSQL 바다아이 10561
17 postgresql postgresql vacuumdb, psql, pg_dump password crontab , pgpass 바다아이 10245
16 postgresql postgresql sequence 퀀 auto_increment . 바다아이 9665
| |









Copyright ⓒ 2001.12. bada-ie.com. All rights reserved.
이 사이트는 리눅스에서 firefox 기준으로 작성되었습니다. 기타 브라우저에서는 다르게 보일 수 있습니다.
[ Ubuntu + GoLang + PostgreSQL + Mariadb ]
서버위치 : 오라클 클라우드 춘천  실행시간 : 0.0628
to webmaster... gogo sea. gogo sea.